<!-- 组件代码如下  现货购物车 -->
<template>
  <div class="shopping-info animate_active"
       :style="shoppingShow ? 'right:0;' : ''">
    <div class="info">
      <p class="title">购物车<span @click="$parent.shoppingShow = !shoppingShow" style="float: right">关闭</span></p>
      <ul class="shopping-ul">
        <li class="flex flex-a-center shopping-li"
            v-for="(item, key) in cartList"
            v-cloak
            :key="item.id">
          <!--<input type="checkbox"/>-->
          <div class="order-item">
            <div class="flex materials-info">
              <div class="info-left">
                <!--<div class="img">-->
                <el-image class="img" :src="item.goods.goodsMainImg"></el-image>
                <!--</div>-->
                <!--                <span>供应商编号：{{ null }}</span>-->
                <span>现货编号：{{ item.goods.goodsCode }}</span>
              </div>

              <ul class="info-right">
                <li v-for="param in item.goodsParam">
                  <span class="span-lable">{{ param.paramName }}</span>
                  <span>{{ param.inputValue }}</span>
                </li>
              </ul>
            </div>
            <div style="margin-top: 20px">
              <el-table :data="item.byNum" border style="width: 500px">
                <el-table-column
                    prop="goodsSpecifications.specificationsName"
                    label="规格">
                </el-table-column>
                <el-table-column
                    prop="goodsSize.sizeName"
                    label="尺码">
                </el-table-column>
                <el-table-column
                    prop="date"
                    label="购买数量">
                  <template slot-scope="scope">
                    <el-input-number @change="handleChange(item.id,scope.row.id,scope.row.buyNum)" :min="0" size="mini"
                                     v-model="scope.row.buyNum"></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="shopping-order-detail">
              <div class="flex flex-a-center detail-item">
                <span class="lable">购买总数</span>
                <div>
                  <el-input-number
                      :controls="false"
                      disabled
                      v-model="item.goodsNum"></el-input-number>
                </div>
              </div>
              <span v-show="item.buyNumber>=item.inventory" style="color:red">库存紧张，订单可能被驳回或备库</span>
              <div v-if="item.range!=null" class="detail-item">
                <span class="lable">阶梯价</span>
                <span v-if="item.range!=null" class="item-span-right">{{ item.range.price }}元/米</span>
              </div>
              <div class="detail-item">
                <span class="lable">现货总额</span>
                <!--<span class="item-span-right red">{{item.num * item.price}}元</span>-->
                <span class="item-span-right red">{{ Number(item.sumMoney) }}元</span>
              </div>

              <!--              <div class="detail-item">
                              <span class="lable">客户折扣</span>
                              <span class="item-span-right red">{{ (Number(item.discount) * 100) + '%' }}</span>
                            </div>-->

              <div class="detail-item">
                <span class="lable">备注</span>
                <span class="item-span-right" style="width: 200px"><el-input
                    type="textarea"
                    :rows="4"
                    @blur="updateBZ(item.id,item.remark)"
                    v-model="item.remark"/></span>
              </div>
              <div class="detail-item">
                <el-button style="background-color: #4c4c4c" type="primary"
                           @click="delCart(item.id)"><span
                    style="color:#f9d532;">删除</span></el-button>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="flex btn-box" style="z-index: 1">
      <div class="shopping flex-a-center">
        <p>
          合计（不含运费）
          <span class="red">{{ cartList.length > 0 ? cartList[0].allPrice : '' }}</span> 元
        </p>
      </div>
      <button type="submit" class="flex-1 Settlement" @click="checkData(),gotolink()">
        提交
      </button>
    </div>
  </div>
</template>
<script>
import {getAction} from "../api/manage";

export default {
  name: "GoodsShopping",
  created() {
    this.getCartList()
  },
  data() {
    return {
      orderSn: '',// 创建订单成功之后的ID
      autohor_token: localStorage.getItem("token"), //token
      allPrice: 0,
      url: {
        list: '/buygoods/getCartList', // 获取购物车列表
        updateByNum: '/buygoods/updateByNum', // 更新购买数量
        updateRemark: '/buygoods/updateRemark', // 更新备注
        // 删除购物车
        delCart: '/buygoods/deleteCart',
        // 创建一条未支付的订单
        createFabricOrder: '/buygoods/createFabricOrder',

        // 不要用哦
        decare: '/cart/decrByNum', //购物车数量减一
        incare: '/cart/incrByNum', // 购物车数量加一
        changeBuyNumber: '/cart/changeBuyNumber', // 手动修改购买数量
      },
      cartList: [], // 查询到的购物车列表
      cartids: [], // 购物车IDS
      shoppingList: [
        {
          id: 1,
          idNum1: '2561IOU',
          idNum2: 'LVII033147',
          info1: 'SUPER110`S',
          info2: '羊毛',
          info3: '260g',
          info4: '人字',
          info5: '米色',
          info6: '150cm',
          num: 2,
          price: '390'
        },
        {
          id: 2,
          idNum1: '2561IOU',
          idNum2: 'LVII033147',
          info1: 'SUPER110`S',
          info2: '羊毛',
          info3: '260g',
          info4: '人字',
          info5: '米色',
          info6: '150cm',
          num: 1,
          price: '390'
        }
      ],
    };
  },
  props: {
    shoppingShow: {
      type: Boolean
    }
  },
  mounted() {
  },
  methods: {

    /**
     * 改变购物车购买数量的方法
     * @param id 大购物车id
     * @param smallid 小购物车id
     * @param num 小购买数量
     */
    handleChange(id, smallid, num) {
      getAction(domain.publicUrl + this.url.updateByNum, {
        'token': this.autohor_token,
        'id': id,
        'smallid': smallid,
        'num': num
      }).then(res => {
        if (res.data.code == 0) {
          this.$message.success('操作成功')
          this.getCartList()
        } else {
          this.$message.error('操作失败')
        }
      })
    },

    changflag() {
      var f = true;
      f = true;
      f = true;
      f = false;
    },

    numberChange(item) {//面料米数的监听事件
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]+)?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      // var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (!reg.test(item.buyNumber)) {
        this.$message.warning("请输入正确的米数,比如1或1.1")
        item.buyNumber = '1';
        this.changeBuyNumberFunc(item.id, item.buyNumber)
        return
      } else {
        let inputnumber = item.buyNumber;//10.234  1.7777
        // alert(inputnumber+"==="+inputnumber.toString().split(".").length)
        item.buyNumber = Math.floor((inputnumber * 1 + 0.09) * 10) / 10;
        this.changeBuyNumberFunc(item.id, item.buyNumber)
        return;

        // if (inputnumber.toString().split(".").length == 0) {
        //   item.buyNumber = inputnumber;
        //   this.changeBuyNumberFunc(item.id, item.buyNumber)
        //   return;
        // } else {
        //   var number_zu = inputnumber.toString().split(".");
        //   // alert("拿了米=="+number_zu)
        //   var jisaun_number = inputnumber.toString().split(".").join("");
        //   // alert("数组=="+number_zu+"==涨肚="+number_zu.length+"=小数点后的=="+number_zu[1].length)
        //   if (number_zu[1].length >= 0 && number_zu[1].length < 2) {
        //     item.buyNumber = inputnumber;
        //     this.changeBuyNumberFunc(item.id, item.buyNumber)
        //     return;
        //   } else if (number_zu[1].length >= 2) {
        //     let num1 = jisaun_number / 100 + 0.1;
        //     let num2 = num1 * 10;
        //     let num3 = num2 / 10;
        //     var number_zu2 = num3.toString().split(".");
        //     let lostnum = number_zu2[0] + "." + number_zu2[1].substring(0, 1)
        //     // var str = num3.substring(0,num3.length-1);//截取第二个到第四个之间的字符 cd
        //     // alert(inputnumber+"==最后孩子=="+num1+"==="+num3+"==最后="+number_zu2+"=="+lostnum)
        //     item.buyNumber = lostnum;
        //     this.changeBuyNumberFunc(item.id, item.buyNumber)
        //     return;
        //   }
        // }
      }
    },
    /**
     * 修改备注
     */
    updateBZ(id, remark) {
      getAction(domain.publicUrl + this.url.updateRemark, {
        'id': id,
        'remark': remark
      }).then(res => {
        if (res.data.code == '0') {
          this.$message.success("修改成功")
        }
      })
    },

    checkData() { // 检查基本信息是否填写
      if (this.$store.state.stooreCode2 == '' || this.$store.state.stooreCode2 == null) {
        this.$message.error("请选择门店")
        return 1
      } else if (this.$store.state.kuaidiID2 == '' || this.$store.state.kuaidiID2 == null) {
        this.$message.error("请选择快递方式")
        return 1
      } else if (this.$store.state.addressType2 == '' || this.$store.state.addressType2 == null) {
        this.$message.error("请选择地址类型")
        return 1
      } else if (this.$store.state.address2 == '' || this.$store.state.address2 == null) {
        this.$message.error("请填写地址")
        return 1
      } else {
        return 0
      }
    },
    // 删除购物车
    delCart(cartid) {
      getAction(domain.publicUrl + this.url.delCart, {'id': cartid}).then(res => {
        if (res.data.code == '0') {
          this.$message.success("删除成功")
          this.cartList = res.data.data
          this.getCartList()
          if (this.cartList.length == 0) {
            this.$parent.shoppingShow = !shoppingShow
          }
        }
      })
    },
    getCartList() { // 查询购物车列表
      this.cartids = []
      let ppp = 0
      getAction(domain.publicUrl + this.url.list, {'token': this.autohor_token}).then(res => {
        if (res.data.code == '0') {
          this.cartList = res.data.data
          if (this.cartList.length > 0) {
            // 统计购物车的总金额
            for (var j = 0; j < this.cartList.length; j++) {
              this.cartids.push(this.cartList[j].id)
              ppp += Number(this.cartList[j].sumMoney)
            }
            this.allPrice = ppp
          } else {
            this.allPrice = 0
          }
        }
      })
    },
    // 购物车减一
    minus(cartID) {

      getAction(domain.publicUrl + this.url.decare, {
        'cartid': cartID,
        'token': this.autohor_token
      }).then(res => {
        if (res.data.code == '0') {
          this.getCartList()
          // this.$message.success(res.data.msg)
        } else if (res.data.code == '1') {
          // this.$message.error(res.data.msg)
        }
      })
      /*if (this.shoppingList[index].num != 1) {
          this.shoppingList[index].num--;
      }*/

    },

    /**
     * 购物车加一
     * @param cartID 购物车 ID
     */
    add(cartID) {
      getAction(domain.publicUrl + this.url.incare, {
        'cartid': cartID,
        'token': this.autohor_token
      }).then(res => {
        if (res.data.code == '0') {
          this.getCartList()
          // this.$message.success(res.data.msg)
        } else if (res.data.code == '1') {
          // this.$message.error(res.data.msg)
        }
      })
    },

    /**
     *手动修改购买米数
     * @param cartid 购物车ID
     * @param buynumber 购买米数
     */
    changeBuyNumberFunc(cartid, buynumber) {

      if (buynumber > 0) {
        getAction(domain.publicUrl + this.url.changeBuyNumber, {
          'cartid': cartid,
          'buyNum': buynumber,
          'token': this.autohor_token
        }).then(res => {
          if (res.data.code == '0') {
            this.getCartList()
            // this.$message.success("操作成功")
          } else if (res.data.code == '1') {
            this.getCartList()
            // this.$message.warning("库存不足")
          } else if (res.data.code == '2') {
            return
          } else if (res.data.code == '500' || res.data.code == '3') {
            this.getCartList()
            this.$message.warning("请输入正确的购买米数")
          }
        })
      } else {
        this.$message.warning("请输入正确的购买米数")
        this.getCartList()
      }
    },

    // 购物车提交订单（创建未支付订单）
    gotolink() {
      if (this.cartList == null || this.cartList.length == 0) {
        return
      }
      if (this.checkData() == 1) {
        return
      }
      getAction(domain.publicUrl + this.url.createFabricOrder, {
        'token': this.autohor_token,
        'packaging': this.$store.state.packageType2,
        'courierId': this.$store.state.kuaidiID2,
        'addressType': this.$store.state.addressType2 == '1' ? "门店地址" : "其他地址",
        'address': this.$store.state.address2,
        'otherOrdersn': this.$store.state.threadSn,
        'goodsCartId': this.cartids.toString(),
        'storeId': this.$store.state.storeid2,
        'storeCode': this.$store.state.stooreCode2,
        'name': this.$store.state.name2,
        'phone': this.$store.state.phone2
      }).then(res => {
        if (res.data.code == '0') {
          this.getCartList()
          this.$message.success(res.data.msg)
          this.shoppingShow = false
          this.orderID = res.data.data
          this.$router.push({path: '/my-order'})
          /*this.$parent.openBuy(this.allPrice, res.data.data)*/
        } else if (res.data.code == '1') {
          this.$message.error(res.data.msg)
        }
      })
    }
  },
};
</script>
<style>
[v-cloak] {
  display: none;
}
</style>
